package com.example.recyclerviewlearn;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.Scroller;

public class CustomizeImageView extends androidx.appcompat.widget.AppCompatImageView {
    private static final String TAG = "CustomizeImageView";

    private ViewGroup mViewGroup;

    private int mStartX = 0;

    private int mStartY = 0;

    private Scroller mScroller = new Scroller(this.getContext());

    public CustomizeImageView(Context context) {
        super(context);
    }

    public CustomizeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomizeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mViewGroup = (ViewGroup) getParent();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG, "onTouchEvent: ");
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                mStartX = (int) event.getX();
                mStartY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i(TAG, "onTouchEvent: startX" + mStartX + "mStartY" + mStartY);
                int curX = (int) event.getX();
                int curY = (int) event.getY();
                Log.i(TAG, "onTouchEvent: curX" + curX + "curY" + curY);
                int delX = curX - mStartX;
                int delY = curY - mStartY;
                mStartX = curX;
                mStartY = curY;
                Log.i(TAG, "onTouchEvent: ACTION_MOVE");
                mViewGroup.scrollBy(-delX, -delY);
                break;
            case MotionEvent.ACTION_UP:
                mScroller.startScroll(mViewGroup.getScrollX(), mViewGroup.getScrollY(),
                        -mViewGroup.getScrollX(), -mViewGroup.getScrollY(), 1000);
                invalidate();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            mViewGroup.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            invalidate();
        }
    }
}
